<?php
namespace Com\Pay;

//威付通微信公众号支付

class WeiFuTongPay{

    private $config = array();

  
    public function __construct($send_data){
        $this->config = $send_data;
    }


    /*生成支付连接*/
    public function getUrl($order_info,$other = array()){
//        $key 	= $this->config['key'];
        /* 获取提交的订单交易金额 */
        $price = $order_info['paymoney'];
        //支付成功后跳转地址
        if(!empty($other['returl'])){
            $returnUrl = $other['returl'];
        }else{
            $returnUrl    = $order_info['return_url'];
        }
        if(!empty($other['callback'])){
            $notifyUrl = $other['callback'];
        }else{
            /* 获取提交的后台回调地址 */
            $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/NotifyCallback/WeifutongpayNotify';
        }

        $Sumprice = $price * 100;
        $order_sn = $order_info['ordernumber'];
        $post_data = array(
            'service' =>   'pay.weixin.jspay',
            'version'    =>     '2.0',
            "mch_id"  => $this->config['mch_id'],
            "is_raw"  =>  '1',
            "out_trade_no"  =>  $order_sn,
            'body' => 'ChangbaoGzh',
            'sub_openid' => $order_info['openid'],  // 测试商户不需要填写
            'total_fee' => $Sumprice,
            'mch_create_ip' => getRealIp(),
            'notify_url'    => $notifyUrl,
            'callback_url'    => $returnUrl,
            'nonce_str'    => mt_rand(11111111111,999999999999),
        );
//        dump($post_data);die;
        $ContentSign = $this->setParam($post_data,$this->config['mch_key'],false); // 计算出Sign
        $post_data['sign'] = $ContentSign; // Sign签名
        $tar_url = 'https://pay.swiftpass.cn/pay/gateway';
        $xml = $this->arrayToXml($post_data);
        $res = $this->https_request($tar_url,$xml);
        $res_arr = xmlToArray($res);
        dump($res_arr);
        exit;
        if($res_arr['result_code'] == '0'){
            $ret = $res_arr['pay_info'];
        }else{
            // 各种原因发起支付失败
            $ret = '';
        }
        return $ret;
    }

    private function setParam($param,$key,$IS_Notify){
        $str = "";
        ksort($param);
        foreach($param as $key1=>$val)  {
            if($IS_Notify && $key1 == 'sign') continue;
            $str.=$key1."=".$val."&";
        }
        $str = rtrim($str,'&');
        $sign = strtoupper(md5($str . '&key=' . $key));
        return $sign;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $a  = file_get_contents('php://input');
        $data = xmlToArray($a);
        $MySign = $this->setParam($data,$this->config['mch_key'],true);
        if($data['sign'] == $MySign){
            if($data['pay_result'] == '0' && $data['status'] == '0'){
                return true;
            }else{
                // 失败
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }


    private function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        //参数不为空则为post请求

        if (!empty($data)){

            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }


    // 去掉所有数组空格
    private function norim($xmlArr){
        $newarr = array();
        foreach ($xmlArr as $key => $value) {
            $key1 = trim($key);
            $value1 = trim($value);
            $newarr[$key1] = $value1;
        }
        return $newarr;
    }


    //数组转XML
    private function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

}
